/*
 * Filename: GetJSONArrayTask.java
 * Description: This class is used to get JSON data from the server
 */

package edu.usc.libtalk.task;

import edu.usc.libtalk.utils.ApplicationService;
import org.json.JSONArray;

import android.os.AsyncTask;
import android.util.Log;
import android.widget.ProgressBar;

public class GetJSONArrayTask extends AsyncTask<String, Integer, JSONArray>{
	
	private static final String TAG = "GetJSONArrayTask";	
	private ProgressBar progressbar;
	private int percent;
	
	public GetJSONArrayTask withProgressBar(ProgressBar progressbar, int percent){
		this.progressbar = progressbar;
		this.percent = percent;
		return this;
	}	
	
	private int lastProgressUpdate = 0;
	@Override
	protected void onProgressUpdate(Integer... changed) {
		if(progressbar != null){
			double scaledChange = (changed[0] - lastProgressUpdate) * percent / 100.0;
			synchronized (progressbar) {
				progressbar.setProgress(progressbar.getProgress() + (int)scaledChange);
			}
			lastProgressUpdate = changed[0];
		}
	}	
	
	@Override
	protected JSONArray doInBackground(String... urls) {
		
		if (urls.length == 0 || urls[0] == null)
			return null;
		JSONArray result = null;
		String url = urls[0];
				
		try {
			publishProgress(30);
			String httpget_result = ApplicationService.executeHttpGet(url);
			
			publishProgress(90);
			result = new JSONArray(httpget_result);
			
		} catch (Exception e) {
			Log.e(TAG, "doInBackground: " + e.toString());
			return null;
		}
		
		publishProgress(100);		
		return result;
	}	
}
